<?php
/**
 * Created by PhpStorm.
 * User: ysk
 * Date: 2021/6/18
 * Time: 18:24
 */

namespace api\base;

use Yii;
use yii\base\Model;
use yii\behaviors\AttributeTypecastBehavior;
use yii\helpers\ArrayHelper;

class BaseApiParams extends Model
{

    public $page_type;

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(),
            [
                'typecast' => [
                    'class' => AttributeTypecastBehavior::className(),
                    // 'attributeTypes' will be composed automatically according to `rules()`
                ],
            ]
        );
    }

    public function validate($attributeNames = null, $clearErrors = true)
    {
        $ret = parent::validate($attributeNames, $clearErrors); // TODO: Change the autogenerated stub
        if (($this->page_type || $this->page_type = 'h5') && !in_array($this->page_type, ['pc', 'h5', 'app'])) {
            $this->addError('page_type', '页面类型错误');
            $ret = false;
        }

        return $ret === true;
    }

    /**
     * 是否由框架自动验证
     * @return bool
     */
    public function isAutoValidate()
    {
        return true;
    }

    public function formName()
    {
        return '';
    }

    public function getErrorsAsString()
    {
        $errors = $this->getErrors();
        $msg    = '';

        foreach ($errors as $field => $errArr) {
            $msg .= join('', $errArr);
        }

        return $msg;
    }

    /**
     * 验证平台权限
     *
     * @param string $attribute 平台字段名
     * @param        $params
     */
//    public function validatePlatformAuth($attribute, $params)
//    {
//        $platform = $this->$attribute;
//
//        if (empty(ApiContext::get()->getRequest()->appid)) {
//            $this->addError($attribute, '缺少appid');
//        }
//
//        /**
//         * @var ApiAuth Yii::$app->apiAuth
//         */
//        if (!Yii::$app->apiAuth->validateAppPlatformAuth(ApiContext::get()->getRequest()->appid, $platform)) {
//            $this->addError($attribute, '无权限操作该平台');
//        }
//    }

}